import axios from 'axios';
import type { AxiosInstance } from 'axios';
import type { HRInterceptorsConfig, HRRequestConfig } from './type';
class HRRequest {
  instacnce: AxiosInstance;
  interceptors?: HRInterceptorsConfig;
  constructor(config: HRRequestConfig) {
    this.instacnce = axios.create(config);
    this.interceptors = config.interceptors;
    this.instacnce.interceptors.request.use(
      this.interceptors?.requestInterceptors,
      this.interceptors?.requestInterceptorsCatch
    );
    this.instacnce.interceptors.response.use(
      this.interceptors?.responseInterceptors,
      this.interceptors?.responseInterceptorsCatch
    );
  }
  request<T>(config: HRRequestConfig): Promise<T> {
    return new Promise((resolve, reject) => {
      this.instacnce
        .request<any, T>(config)
        .then((res) => {
          resolve(res);
        })
        .catch((error) => {
          reject(error);
        });
    });
  }
  get<T>(config: HRRequestConfig): Promise<T> {
    return this.request<T>({
      ...config,
      method: 'GET'
    });
  }
  post<T>(config: HRRequestConfig): Promise<T> {
    return this.request<T>({
      ...config,
      method: 'POST'
    });
  }
  delete<T>(config: HRRequestConfig): Promise<T> {
    return this.request<T>({
      ...config,
      method: 'DELETE'
    });
  }
  patch<T>(config: HRRequestConfig): Promise<T> {
    return this.request<T>({
      ...config,
      method: 'PATCH'
    });
  }
}

export default HRRequest;
